package com.java.upload_file.config;

import org.apache.tomcat.util.http.fileupload.impl.FileSizeLimitExceededException;
import org.apache.tomcat.util.http.fileupload.impl.SizeLimitExceededException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.multipart.MultipartException;

import java.util.HashMap;
import java.util.Map;

@RestControllerAdvice
public class GlobalExceptionHandler {

    static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(value = MultipartException.class)
    @ResponseBody
    public Map<String, Object> handleBusinessException(MaxUploadSizeExceededException ex) {
        Map<String, Object> result = new HashMap<>();
        String msg;
        if (ex.getCause().getCause() instanceof FileSizeLimitExceededException) {
            logger.error(ex.getMessage());
            msg = "上传文件过大[单文件大小不得超过" + 10 + "]";
        } else if (ex.getCause().getCause() instanceof SizeLimitExceededException) {
            logger.error(ex.getMessage());
            msg = "上传文件过大[总上传文件大小不得超过" + 10 + "]";
        } else {
            msg = "上传文件失败";
        }
        result.put("code", "500");
        result.put("success", false);
        result.put("msg", msg);
        return result;
    }
}